
import { getToken, setToken, removeToken } from '@/utils/auth'
import { loginAPI } from '@/api'
import { getUserProfileAPI, getUserPhotoAPI } from '@/api/user'
import router from '@/router'
const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: {}
  }
}
const state = getDefaultState

const mutations = {
  SET_USER(state, value) {
    state.userInfo = value
  },
  REMOVE_USER(state) {
    state.userInfo
  },
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN(state, newToken) {
    state.token = newToken
    setToken(newToken)
  },
  REMOVE_TOKEN(state) {
    state.token = ''
    removeToken()
  }
}

const actions = {
  async getUserInfoActions({ commit }) {
    const { data: userObj } = await getUserProfileAPI()
    const { data: photoObj } = await getUserPhotoAPI(userObj.userId)
    commit('SET_USER', { ...userObj, ...photoObj })
  },
  async loginActions({ commit }, value) {
    const arr = await loginAPI(value)
    const [, res] = arr
    commit('SET_TOKEN', res.data)
    return arr
  },
  async logoutActions(store) {
    removeToken()
    store.commit('RESET_STATE')
    router.replace(`/login?redirect=${router.fullpath}`)
  }
}

// get user info

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

